package Homework;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test {

	public static void main(String[] args) throws Exception {
		/*
		 * 先获取class对象
		 * 1.类名.class
		 * 2.对象.getClass
		 * 3.Class.forName(类的全路径)
		 */
		Class<Student> clazz =Student.class;
		/*
		 * Student student = new Student();
		 *	Class<Student> clazz = (Class<Student>) student.getClass();
		 */
		//Class<Student> clazz = (Class<Student>) Class.forName("Student");
		
		//获取类的某个公有属性
		Field field = clazz.getField("gender");
		System.out.println(field);
		//获取类的全部公有属性
		Field[] fields = clazz.getFields();
		for (Field field2 : fields) {
			System.out.println(field2);
		}
		//获取类的某个属性
		Field field2 = clazz.getDeclaredField("name");
		System.out.println(field2);
		//获取类的全部属性
		Field[] fields2 = clazz.getDeclaredFields();
		for (Field field3 : fields2) {
			System.out.println(field3);
		}
		
		//获取类及其父类的某个公有成员方法
		Method method = clazz.getMethod("setName", String .class);
		System.out.println(method);
		//获取类及其父类的所有公有成员方法
		Method[] methods = clazz.getMethods();
		for (Method method2 : methods) {
			System.out.println(method2);
		}
		
		//获取类自定义的某个成员方法
		Method method2 = clazz.getDeclaredMethod("info1");
		System.out.println(method2);
		//获取类自定义的所有成员方法
		Method[] methods2 = clazz.getDeclaredMethods();
		for (Method method3 : methods2) {
			System.out.println(method3);
		}
		
		//有参构造方法
		Constructor<Student> constructor = clazz.getConstructor(String.class,int.class,String .class);
		//传入参数
		Student student = constructor.newInstance("Tom",27,"Basketball");
		System.out.println(student);
		
		//无参构造方法
		Constructor<Student> constructor2 = clazz.getConstructor();
		Student student2 = constructor2.newInstance();
		System.out.println(student2);
		
		
		//通过反射调用无参构造方法创建对象
		Student student3 = clazz.newInstance();
		//获取类的全部方法
		Field[] fields3 = clazz.getDeclaredFields();
		//循环遍历所有方法
		for (Field field3 : fields3) {
			//非公有属性需要先获取访问权限
			field3.setAccessible(true);
			if("name".equals(field3.getName())) {
				field3.set(student3, "Tom");
			}
			if("age".equals(field3.getName())) {
				field3.set(student3, 24);
			}
			if("hobby".equals(field3.getName())) {
				field3.set(student3, "Basketball");
			}
		}
		//调用toString方法
		Method method3 = clazz.getMethod("toString");
		String  info = (String) method3.invoke(student3);
		System.out.println(info);
		
	}

}
